import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../heartbeat/parts/magma_report_dialog.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/blueprint/chat_model.dart';

/// 私聊对话视图模型
class PrivateChatViewModel extends BaseViewModel {
  String _partnerId = '';
  String get partnerId => _partnerId;

  final TextEditingController textInput = TextEditingController();

  /// 获取当前用户
  UserModel? get activeUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get hasSession => appState.userStore.isLoggedIn;

  /// 初始化数据
  void prepareData(String partnerId) {
    _partnerId = partnerId;

    // 标记与该用户的所有消息为已读
    if (hasSession && activeUser != null) {
      appState.chatCoordinator.markConversationAsRead(
        currentUserId: activeUser!.id,
        otherUserId: _partnerId,
      );
    }

    notifyListeners();
  }

  /// 获取对方用户信息
  UserModel? get partnerUser {
    return appState.userStore.getUserById(_partnerId);
  }

  /// 获取聊天记录
  List<ChatMessageModel> get conversation {
    if (!hasSession || activeUser == null) return [];
    return appState.chatCoordinator.fetchConversation(
      currentUserId: activeUser!.id,
      otherUserId: _partnerId,
    );
  }

  /// 发送文本消息
  Future<bool> transmitMessage() async {
    if (!hasSession || activeUser == null) return false;
    if (textInput.text.trim().isEmpty) return false;

    final result = await appState.chatCoordinator.dispatchTextMessage(
      senderId: activeUser!.id,
      receiverId: _partnerId,
      content: textInput.text.trim(),
    );

    if (result) {
      textInput.clear();
      notifyListeners();
    }

    return result;
  }

  /// 导航到拨打电话页面
  void navigateToCallScreen() {
    QR.to(MagmaRouter.videoCallPath.replaceAll(':targetUserId', _partnerId));
  }

  /// 举报用户
  Future<void> reportUser() async {
    if (!hasSession || activeUser == null) return;

    // 删除与对方用户的所有对话
    await appState.chatCoordinator.deleteConversation(
      currentUserId: activeUser!.id,
      otherUserId: _partnerId,
    );
  }

  @override
  void dispose() {
    textInput.dispose();
    super.dispose();
  }
}

/// 私聊对话页面
class SingleChatStory extends StatefulWidget {
  final String userId;

  const SingleChatStory({super.key, required this.userId});

  @override
  State<SingleChatStory> createState() => _SingleChatStoryState();
}

class _SingleChatStoryState extends State<SingleChatStory> {
  final ScrollController _messageScrollController = ScrollController();

  @override
  void dispose() {
    _messageScrollController.dispose();
    super.dispose();
  }

  void _jumpToBottom() {
    if (_messageScrollController.hasClients) {
      Future.delayed(const Duration(milliseconds: 100), () {
        _messageScrollController.animateTo(
          _messageScrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<PrivateChatViewModel>.reactive(
      viewModelBuilder: () => PrivateChatViewModel(),
      onViewModelReady: (viewModel) {
        viewModel.prepareData(widget.userId);
        WidgetsBinding.instance.addPostFrameCallback((_) => _jumpToBottom());
      },
      builder: (context, viewModel, child) {
        final partner = viewModel.partnerUser;

        if (partner == null) {
          return Scaffold(
            backgroundColor: MagmaColor.black,
            body: Center(
              child: Text(
                'User not found',
              ).inter(fontSize: 16.sp, color: MagmaColor.white),
            ),
          );
        }

        WidgetsBinding.instance.addPostFrameCallback((_) => _jumpToBottom());

        return Scaffold(
          backgroundColor: MagmaColor.black,
          appBar: AppBar(
            backgroundColor: MagmaColor.black,
            leading: MagmaTap(
              onTap: () => QR.back(),
              child: Container(
                padding: EdgeInsets.all(14.w),
                child: Image.asset(
                  MagmaConstant.back,
                  width: 16.w,
                  height: 16.w,
                  color: MagmaColor.white,
                ),
              ),
            ),
            title: Text('Chat').blackHanSans(
              fontSize: 24.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w400,
            ),
            centerTitle: true,
            actions: [
              MagmaTap(
                onTap: () => _showReportDialog(context, viewModel),
                child: Padding(
                  padding: EdgeInsets.only(right: 20.w),
                  child: Image.asset(
                    MagmaConstant.report,
                    width: 26.w,
                    height: 26.w,
                    color: MagmaColor.white,
                  ),
                ),
              ),
            ],
          ),
          body: Column(
            children: [
              // 消息列表
              Expanded(
                child:
                    viewModel.conversation.isEmpty
                        ? Center(
                          child: Text('No messages yet').inter(
                            fontSize: 14.sp,
                            color: MagmaColor.white.withOpacity(0.5),
                          ),
                        )
                        : ListView.builder(
                          controller: _messageScrollController,
                          padding: EdgeInsets.symmetric(
                            horizontal: 16.w,
                            vertical: 12.h,
                          ),
                          itemCount: viewModel.conversation.length,
                          itemBuilder: (context, index) {
                            final message = viewModel.conversation[index];
                            final isCurrentUser =
                                viewModel.hasSession &&
                                message.senderId == viewModel.activeUser?.id;

                            return _assembleMessageBubble(
                              message,
                              isCurrentUser,
                              partner,
                              viewModel.activeUser,
                            );
                          },
                        ),
              ),

              // 输入框
              _constructInputSection(viewModel),
            ],
          ),
        );
      },
    );
  }

  /// 组装消息气泡
  Widget _assembleMessageBubble(
    ChatMessageModel message,
    bool isCurrentUser,
    UserModel partner,
    UserModel? activeUser,
  ) {
    return Padding(
      padding: EdgeInsets.only(bottom: 16.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment:
            isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: [
          if (!isCurrentUser) ...[
            // 对方消息：左侧头像
            CircleAvatar(
              radius: 20.r,
              backgroundImage: AssetImage(partner.avatar),
            ),
            SizedBox(width: 8.w),
          ],

          // 消息气泡
          Flexible(
            child: Container(
              margin: EdgeInsets.only(
                // 对方消息：右边距
                right: !isCurrentUser ? 36.w : 0,
                // 我方消息：左边距
                left: isCurrentUser ? 36.w : 0,
              ),
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color:
                    isCurrentUser
                        ? MagmaColor.green
                        : MagmaColor.white.withOpacity(0.15),
                borderRadius:
                    isCurrentUser
                        ? BorderRadius.only(
                          topLeft: Radius.circular(16.r),
                          topRight: Radius.circular(2.r),
                          bottomLeft: Radius.circular(16.r),
                          bottomRight: Radius.circular(16.r),
                        )
                        : BorderRadius.only(
                          topLeft: Radius.circular(2.r),
                          topRight: Radius.circular(16.r),
                          bottomLeft: Radius.circular(16.r),
                          bottomRight: Radius.circular(16.r),
                        ),
              ),
              child: Text(message.content).inter(
                fontSize: 14.sp,
                color: isCurrentUser ? MagmaColor.black : MagmaColor.white,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),

          if (isCurrentUser) ...[
            // 当前用户消息：右侧头像
            SizedBox(width: 8.w),
            CircleAvatar(
              radius: 20.r,
              backgroundImage: AssetImage(
                activeUser?.avatar ?? MagmaConstant.avatar1,
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建输入框区域
  Widget _constructInputSection(PrivateChatViewModel viewModel) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 装饰图片
        Image.asset(
          MagmaConstant.decoration,
          width: double.infinity,
          fit: BoxFit.fitWidth,
        ),

        // 输入框区域
        Container(
          padding: EdgeInsets.fromLTRB(
            16.w,
            12.h,
            16.w,
            MediaQuery.of(context).padding.bottom + 12.h,
          ),
          color: MagmaColor.black,
          child: SizedBox(
            height: 56.h,
            child: Container(
              decoration: BoxDecoration(
                color: MagmaColor.white,
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Row(
                children: [
                  // 输入框
                  Expanded(
                    child: TextField(
                      controller: viewModel.textInput,
                      style: TextStyle(
                        color: MagmaColor.black,
                        fontSize: 14.sp,
                      ),
                      decoration: InputDecoration(
                        hintText: 'Say Something...',
                        hintStyle: TextStyle(
                          color: MagmaColor.black.withOpacity(0.6),
                          fontSize: 14.sp,
                        ),
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 20.w,
                          vertical: 16.h,
                        ),
                      ),
                      onSubmitted: (_) => viewModel.transmitMessage(),
                    ),
                  ),

                  // 拨打电话按钮
                  Padding(
                    padding: EdgeInsets.only(right: 8.w),
                    child: MagmaTap(
                      onTap: viewModel.navigateToCallScreen,
                      child: Container(
                        padding: EdgeInsets.all(10.w),
                        decoration: BoxDecoration(
                          color: MagmaColor.purple,
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child: Image.asset(
                          MagmaConstant.call,
                          width: 20.w,
                          height: 20.w,
                        ),
                      ),
                    ),
                  ),

                  // Send 按钮
                  Padding(
                    padding: EdgeInsets.only(right: 8.w),
                    child: MagmaTap(
                      onTap: viewModel.transmitMessage,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 20.w,
                          vertical: 10.h,
                        ),
                        decoration: BoxDecoration(
                          color: MagmaColor.purple,
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child: Text('Send').blackHanSans(
                          fontSize: 18.sp,
                          color: MagmaColor.black,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 显示举报对话框
  void _showReportDialog(BuildContext context, PrivateChatViewModel viewModel) {
    MagmaReportDialog.showReportDialog(
      context,
      title: 'Report User',
      subtitle: 'Please select a reason for reporting this user',
      onReportSubmitted: (option) async {
        // 执行举报用户逻辑 - 删除所有消息和对话
        await viewModel.reportUser();
        if (!mounted) return;
        // 刷新视图
        viewModel.notifyListeners();
        // 返回上一页
        QR.back();
        MagmaToast.success(context, title: 'Report submitted successfully.');
      },
    );
  }
}
